package com.googlecode.likesql.converter;

import java.util.LinkedList;
import java.util.List;

import com.googlecode.likesql.constant.SqlChar;
import com.googlecode.likesql.constant.SqlConstant;
import com.googlecode.likesql.expression.ArrayExp;
import com.googlecode.likesql.utils.ArrayUtils;
import com.googlecode.likesql.utils.StringUtils;

/**
 * This object is to convert {@link ArrayExp} to a SQL string or template.
 * @author Johny Huang
 * @since 0.1
 */
public class ArrayExpConverter implements Converter {

	public String toTemplate(Object obj) {
		ArrayExp ie=(ArrayExp)obj;
		if(ie==null || ie.getArray()==null){
			return StringUtils.EMPTY;
		}
		Object[] array=ie.getArray();
		StringBuffer sb=new StringBuffer();
		if(ArrayUtils.isNotEmpty(array)){			
		    int lastIndex=array.length-1;
		    for(int i=0;i<lastIndex;i++){
		    	sb.append(SqlConstant.CHAR_FOR_REPLACE).append(SqlChar.COMMA);
		    }
		    sb.append(SqlConstant.CHAR_FOR_REPLACE);
		}
		return sb.toString();
	}
	
	public String toSql(Object obj){
		ArrayExp ie=(ArrayExp)obj;
		if(ie==null || ie.getArray()==null){
			return StringUtils.EMPTY;
		}
		Object[] array=ie.getArray();
		StringBuffer sb=new StringBuffer();
		if(ArrayUtils.isNotEmpty(array)){			
		    int lastIndex=array.length-1;
		    Converter cvt=null;
		    for(int i=0;i<array.length;i++){
		    	if(array[i]==null){
		    		cvt=ConverterTable.getInstance().getConverter("null");
		    	}else{
		    		cvt=ConverterTable.getInstance().getConverter(array[i].getClass().getName());
		    	}
		    	sb.append(cvt.toSql(array[i]));
		    	if(i!=lastIndex){
		    		sb.append(SqlChar.COMMA);
		    	}
		    }
		}
		return sb.toString();
	}

	public List toValueList(Object obj) {
		ArrayExp ae=(ArrayExp)obj;
		Object[] values=ae.getArray();
		List list=new LinkedList();
		for(int i=0;i<values.length;i++){
			list.add(values[i]);
		}
		return list;
	}
}
